<template>
    <el-drawer v-model="drawerVisible" title="详情" direction="rtl" size="90%" :with-header="true"
        style="background: #F7F7F7;">
        <div class="main">
            <div class="video">
                <!-- 播放器容器 -->
                <div id="player"></div>
                <!-- 延迟显示 -->
                <div v-if="currentLatency !== null" class="latency-display">
                    延迟: {{ currentLatency }}秒
                </div>
                <!-- 停止直播按钮 -->
                <button @click="handleStopLive"
                    style="border-radius: 5px;border: 1px solid rgb(247, 247, 247);display: flex;align-items: center;padding: 3px;position: absolute;top: 80px;background-color: rgba(0,0,0,0.2);left: 405px;">
                    <img src="../assets/guan.png" alt="" style="width: 15px;height: 15px;">
                    <div style="color: white;">强制关播</div>
                </button>
            </div>
            <div class="center">
                <div class="center-top">
                    <div class="square">
                        <div class="label">直播标题: </div>
                        <div class="content">{{ liveDetail.livestreamTitle || '--' }}</div>
                    </div>
                    <div class="square">
                        <div class="label">开播时间: </div>
                        <div class="content">{{ formatDate(liveDetail.livestreamStartTime) || '--' }}</div>
                    </div>
                    <div class="square">
                        <div class="label">开播介绍: </div>
                        <div class="content">{{ liveDetail.livestreamIntroduce || '--' }}</div>
                    </div>
                    <div class="square">
                        <div class="label">直播封面: </div>
                        <div class="content">
                            <img v-if="liveDetail.reservationCover" :src="liveDetail.reservationCover" alt="直播封面"
                                style="width: 50px;height: 50px;border-radius: 8px;">
                            <span v-else>--</span>
                        </div>
                    </div>
                </div>
                <!-- 图表 -->
                <div class="center-bottom">
                    <div style="padding: 10px;font-weight: 700;"> 直播延迟</div>
                    <broken :options="flowchartOptions" />
                </div>
            </div>
            <div class="right">
                <div class="right-top" style="margin-bottom: 10px;  height: 195px;">
                    <div>
                        <div style="font-weight: 700;">直播数据</div>
                        <div class="data-con">
                            <div>
                                <div class="square">
                                    <div class="label">观看人数</div>
                                    <div class="content">{{ formatNumber(liveDetail.viewCount) || 0 }}</div>
                                </div>
                                <div class="square">
                                    <div class="label">完播率</div>
                                    <div class="content">85%</div>
                                </div>
                            </div>
                            <div>
                                <div class="square">
                                    <div class="label">分享次数</div>
                                    <div class="content">{{ formatNumber(liveDetail.livestreamShareNum) || 0 }}</div>
                                </div>
                                <div class="square">
                                    <div class="label">人均观看时长</div>
                                    <div class="content">12min</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="center-bottom">
                    <div class="audience" style="display: flex;flex-direction: column;">
                        <div style="padding: 10px;font-weight: 700;">直播趋势图</div>
                        <broken :options="trendChartOptions" />
                    </div>
                </div>
            </div>
        </div>

        <div class="list">
            <div class="header-one ">
                <div style="margin-bottom:10px;font-weight: 700;">违规提醒</div>
                <div class="audience-list">
                    <div style="display: flex;flex-direction: column;" v-for="item in banlevel" :key="item.id">
                        <div
                            style="display: flex;align-items: center;border-bottom: 1px solid rgb(240, 240, 240);padding: 5px;">
                            <el-button color="red" plain size="small" :style="{ width: '55px' }">{{ item.type
                                }}</el-button>
                            <p style="margin: 0 10px;font-size: 13px;">{{ item.reason }}</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="header-one ">
                <div style="margin-bottom:10px ;font-weight: 700;">互动评论</div>
                <div class="audience-list">
                    <div style="display: flex;flex-direction: column;" v-for="item in banreasons" :key="item.id">
                        <div
                            style="display: flex;align-items: center;border-bottom: 1px solid rgb(240, 240, 240);padding: 5px;">
                            <div>{{ item.name }}:</div>
                            <p style="margin: 0 10px;font-size: 13px;color: rgb(197, 197, 197);">{{ item.title }}</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="right-bottom" style="height: 220px;box-sizing: border-box;padding: 5px;">
                <div class="audience" style="display: flex;align-items: center;justify-content: space-between;">
                    <div style="font-weight: 700;">在线观众</div>
                    <el-input v-model="name" placeholder="请输入观众名称" clearable
                        style="width: 220px;height: 30px"></el-input>
                </div>
                <div class="audience-list">
                    <div v-for="item in audience" :key="item.id" class="audience-item">
                        <div class="avatar">
                            <div style="display: flex; align-items: center;">
                                <img :src="item.img" />
                                <span style="margin-left: 10px;">{{ item.name }}</span>
                            </div>
                            <div>
                                <el-button size="small" style="background-color: rgb(246, 170, 53); color: white;"
                                    @click="handleKick(item)">
                                    踢出
                                </el-button>
                                <el-button size="small" :disabled="!!item.timer" :style="{
                                    width: '50px',
                                    backgroundColor: item.timer ? 'rgb(228, 244, 255)' : 'rgb(121, 136, 154)',
                                    color: item.timer ? '#409EFF' : '#fff'
                                }" @click="handleBan(item)">
                                    {{ item.timer ? item.countText : '禁言' }}
                                </el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </el-drawer>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, reactive, defineProps, defineEmits, watch } from 'vue'
import broken from '../components/broken.vue';
import { ElMessageBox, ElMessage } from 'element-plus'
import { details } from '../api/live'

const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
    rowData: {
        type: Object,
        default: () => ({})
    }
})

const emit = defineEmits(['update:visible'])

// 直播详情数据
const liveDetail = ref({})
const drawerVisible = ref(props.visible)
const keyword = ref('')
const name = ref('')

// 播放器相关
const MAX_LATENCY = 3;       // 最大延迟（秒）
const CATCHUP_GAP = 0.5;     // 追赶时保留缓冲（秒）
const CHECK_INTERVAL = 2000; // 检查间隔（毫秒）
const MAX_DATA_POINTS = 30;  // 图表保留最大点数

const currentLatency = ref(null);
const latencyData = reactive({
    labels: [],
    values: []
});

let playerInstance = null;
let latencyCheckInterval = null;

// 初始化播放器
const initPlayer = (url) => {
    // 确保HLS.js和OvenPlayer已加载
    if (window.Hls && window.OvenPlayer) {
        playerInstance = OvenPlayer.create('player', {
            sources: [{
                type: "llhls",
                file: url || "http://flvvideo.lxi-tech.com/app/12test/llhls.m3u8"
            }],
            autoStart: true
        });

        // 开始检测延迟
        startLatencyMonitoring();
    } else {
        console.error('HLS.js or OvenPlayer not loaded');
    }
};

// 开始延迟监控
const startLatencyMonitoring = () => {
    latencyCheckInterval = setInterval(() => {
        try {
            const position = playerInstance.getPosition?.();
            const duration = playerInstance.getDuration?.();

            if (typeof position !== 'number' || typeof duration !== 'number') {
                return; // 播放器还没准备好
            }

            const latency = duration - position;
            currentLatency.value = latency.toFixed(2);

            // 更新图表数据
            const now = new Date().toLocaleTimeString();
            latencyData.labels.push(now);
            latencyData.values.push(latency);

            if (latencyData.labels.length > MAX_DATA_POINTS) {
                latencyData.labels.shift();
                latencyData.values.shift();
            }

            // 更新趋势图
            updateFlowchart();

            // 延迟过大追赶
            if (latency > MAX_LATENCY) {
                console.warn(`[LL-HLS] 延迟 ${latency.toFixed(2)} 秒，追赶中...`);
                playerInstance.seek(duration - CATCHUP_GAP);
            }
        } catch (err) {
            console.error(err);
        }
    }, CHECK_INTERVAL);
};

// 强制关播
const handleStopLive = () => {
    ElMessageBox.confirm(
        '确定要强制关闭当前直播吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        ElMessage.success('已发送关播指令');
        // 这里可以添加实际调用关播接口的逻辑
    }).catch(() => {
        // 取消操作
    });
}

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '--'
    const date = new Date(dateString)
    return date.toLocaleString()
}

// 格式化数字
const formatNumber = (num) => {
    if (!num) return '0'
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
}

// 直播趋势图配置
const trendChartOptions = ref({
    tooltip: {
        trigger: 'axis'
    },
    legend: {
        show: false
    },
    xAxis: {
        type: 'category',
        data: ['10:00', '10:05', '10:10', '10:15', '10:20', '10:25', '10:30']
    },
    yAxis: {
        type: 'value',
        name: ''
    },
    series: [
        {
            name: '进房人数',
            type: 'line',
            data: [50, 52, 550, 458, 460, 465, 470],
            smooth: true,
        },
        {
            name: '在线人数',
            type: 'line',
            data: [250, 300, 400, 458, 450, 440, 400],
            smooth: true,
        },
        {
            name: '离开人数',
            type: 'line',
            data: [100, 150, 200, 459, 460, 400, 480],
            smooth: true,
        },
        {
            name: '曝光次数',
            type: 'line',
            data: [200, 300, 270, 400, 320, 500, 100],
            smooth: true,
        }
    ]
});

// 更新趋势图
const updateFlowchart = () => {
    flowchartOptions.value = {
        ...flowchartOptions.value,
        xAxis: {
            type: 'category',
            data: latencyData.labels
        },
        series: [
            ...flowchartOptions.value.series,
            {
                name: '直播延迟',
                type: 'line',
                data: latencyData.values.map(v => v.toFixed(2))
            }
        ]
    };
};

// 延迟图表配置
const flowchartOptions = ref({
    tooltip: {
        trigger: 'axis'
    },
    xAxis: {
        type: 'category',
        data: []
    },
    yAxis: {
        type: 'value'
    },
    series: []
})

// 监听父组件传入的visible变化
watch(() => props.visible, (newVal) => {
    drawerVisible.value = newVal
})

// 监听drawerVisible变化并通知父组件
watch(drawerVisible, (newVal) => {
    emit('update:visible', newVal)
})

// 监听drawerVisible变化，当打开时获取详情
watch(drawerVisible, async (newVal) => {
    if (newVal && props.rowData.id) {
        try {
            const res = await details(props.rowData.id)
            if (res.success && res.code === 0) {
                liveDetail.value = res.data
                // 初始化播放器
                initPlayer(res.data.livePlayUrl)
            }
        } catch (error) {
            console.error('获取直播详情失败:', error)
            ElMessage.error('获取直播详情失败')
        }
    }
})

// 观众管理相关数据
const audience = ref([
    { id: 1, img: '../assets/1.jpg', name: '张三', banLevel: 0, timer: null, countText: '' },
    { id: 2, img: '../assets/2.jpg', name: 'Liming', banLevel: 0, timer: null, countText: '' },
    { id: 3, img: '../assets/3.jpg', name: '王五', banLevel: 0, timer: null, countText: '' },
    { id: 4, img: '../assets/2.jpg', name: '赵六', banLevel: 0, timer: null, countText: '' },
    { id: 5, img: '../assets/2.jpg', name: '赵六', banLevel: 0, timer: null, countText: '' },
    { id: 6, img: '../assets/2.jpg', name: '赵六', banLevel: 0, timer: null, countText: '' },
])

// 违规提醒数据
const banlevel = ref([
    { id: 1, type: '用户举报', reason: '主播涉及到"百分百治病/伪造商品销量"' },
    { id: 2, type: '侵权盗播', reason: '主播涉及到"未授权影视剧/盗用他人直播内容"' },
    { id: 3, type: '欺诈诱导', reason: '主播涉及到"刷礼物解锁私密视频"/"转账返利"' },
    { id: 4, type: '敏感词语', reason: '主播涉及到"百分百治病"' },
    { id: 5, type: '政治敏感', reason: '主播涉及到"曲解国家政策/传播反动言论/敏感事件讨论"' },
    { id: 6, type: '涉黄低俗', reason: '主播涉及到"暴露敏感部位/性暗示动作/色情音效"' },
])

// 互动评论数据
const banreasons = ref([
    { id: 1, name: '张三', title: '主播涉及到"百分百治病/伪造商品销量"' },
    { id: 2, name: 'lisi', title: '主播涉及到"百分百治病/伪造商品销量"' },
    { id: 3, name: '王五', title: '主播涉及到"百分百治病/伪造商品销量"' },
    { id: 4, name: '赵六', title: '主播涉及到"百分百治病/伪造商品销量"' },
    { id: 5, name: 'sfdsfsd', title: '主播涉及到"百分百治病/伪造商品销量"' },
    { id: 6, name: 'xjisanl', title: '主播涉及到"百分百治病/伪造商品销量"' },
])

// 禁言时长阶梯（分钟）
const banMinutes = [1, 5, 15, 30]

// 禁言逻辑
const handleBan = (item) => {
    if (item.timer) return          // 正在倒计时

    // 计算本次禁言分钟
    const level = Math.min(item.banLevel, banMinutes.length - 1)
    const minutes = banMinutes[level]
    let leftSeconds = minutes * 60
    item.banLevel = Math.min(item.banLevel + 1, banMinutes.length - 1)

    // 立即显示一次
    item.countText = formatTime(leftSeconds)

    // 启动定时器
    item.timer = setInterval(() => {
        leftSeconds--
        if (leftSeconds <= 0) {
            clearInterval(item.timer)
            item.timer = null
        } else {
            item.countText = formatTime(leftSeconds)
        }
    }, 1000)
}

// 秒数转 mm:ss
const formatTime = (sec) => {
    const m = String(Math.floor(sec / 60)).padStart(2, '0')
    const s = String(sec % 60).padStart(2, '0')
    return `${m}:${s}`
}

// 踢出
const handleKick = (item) => {
    ElMessageBox.confirm(
        `确定要踢出观众"${item.name}"吗？`,
        '踢出确认',
        {
            confirmButtonText: '踢出',
            cancelButtonText: '取消',
            type: 'warning'
        }
    )
        .then(() => {
            const index = audience.value.findIndex(v => v.id === item.id)
            if (index > -1) {
                const target = audience.value[index]
                if (target.timer) {
                    clearInterval(target.timer)
                    target.timer = null
                }
                audience.value.splice(index, 1)
                ElMessage.success(`已踢出观众 ${item.name}`)
            }
        })
        .catch(() => {
            // 取消操作
        })
}

// 在组件挂载时动态加载播放器脚本
onMounted(() => {
    // 动态加载CDN
    const loadScript = (src) => {
        return new Promise((resolve, reject) => {
            const script = document.createElement('script');
            script.src = src;
            script.onload = resolve;
            script.onerror = reject;
            document.head.appendChild(script);
        });
    };

    Promise.all([
        loadScript('https://cdn.jsdelivr.net/npm/hls.js@1.4.12/dist/hls.min.js'),
        loadScript('https://cdn.jsdelivr.net/npm/ovenplayer/dist/ovenplayer.min.js')
    ]).catch(err => {
        console.error('Failed to load player scripts:', err);
    });
});

// 在组件卸载时清理
onUnmounted(() => {
    if (latencyCheckInterval) {
        clearInterval(latencyCheckInterval);
    }
    if (playerInstance) {
        playerInstance.remove();
    }
});
</script>

<style scoped lang="scss">
.main {
    display: flex;
    margin-top: -20px;

    .video {
        width: 40%;
        height: 440px;
        position: relative;

        #player {
            width: 100%;
            height: 100%;
        }

        .latency-display {
            position: absolute;
            bottom: 10px;
            right: 10px;
            background: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
        }
    }

    .center-bottom {
        width: 396px;
        height: 215px;
        background: #FFFFFF;
        border-radius: 10px;
    }

    .center {
        margin-left: 20px;

        .center-top,
        .center-bottom {
            width: 396px;
            height: 215px;
            background: #FFFFFF;
            border-radius: 10px;
        }

        .center-top {
            .square {
                display: flex;
                padding: 10px;

                .label {
                    font-size: 14px;
                    color: #999999;
                    min-width: 60px;
                }

                .content {
                    font-size: 14px;
                    color: #333;
                    font-weight: 500;
                    margin-left: 10px;

                    img {
                        width: 50px;
                        height: 50px;
                        border-radius: 8px;
                    }
                }
            }
        }

        .center-bottom {
            margin-top: 10px;
        }
    }

    .right {
        margin-left: 20px;

        .right-top,
        .right-bottom {
            width: 380px;
            height: 200px;
            background: #FFFFFF;
            border-radius: 10px;

            .audience-list {
                height: 160px;
                overflow-y: auto;
                scrollbar-width: none;
                -ms-overflow-style: none;

                &::-webkit-scrollbar {
                    display: none;
                }
            }

            .audience-item {
                display: flex;
                flex-direction: column;
                padding: 0 8px;

                .avatar {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    border-bottom: 1px double #c0c4cc;
                    padding: 2px;

                    img {
                        width: 30px;
                        height: 30px;
                        border-radius: 50%;
                    }
                }
            }
        }

        .right-top {
            padding: 10px;

            .data-con {
                display: flex;
            }

            .square {
                width: 140px;
                height: 30px;
                background: #F7F7F7;
                border-radius: 10px;
                display: flex;
                flex-direction: column;
                padding: 10px 20px 20px 20px;
                margin-right: 10px;
                margin-top: 10px;

                .label {
                    font-size: 14px;
                    color: #999;
                }

                .content {
                    font-family: PingFang SC, PingFang SC;
                    font-weight: 800;
                    font-size: 16px;
                    color: #2D7AF7;
                }
            }
        }

        .right-bottom {
            margin-top: 10px;

            .audience {
                display: flex;
                justify-content: space-between;
                padding: 5px 10px;
            }
        }
    }
}

.list {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: auto;
    border-radius: 10px;
    margin-top: 20px;

    .audience-list {
        height: 160px;
        overflow-y: auto;
        scrollbar-width: none;
        -ms-overflow-style: none;

        &::-webkit-scrollbar {
            display: none;
        }
    }

    .header-one {
        width: 31%;
        height: 200px;
        padding: 10px;
        display: flex;
        flex-direction: column;
        margin-bottom: 10px;
        background-color: white;
        border-radius: 12px;
    }
}
</style>